home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-02 / comp-pas.zip / TUTORPAS.ZIP / TUTOR6.DOC < prev    next >
Text File  |  1988-09-04  |  44KB  |  1,247 lines

  1. OPA A
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.                             LET'S BUILD A COMPILER!
  29.  
  30.                                        By
  31.  
  32.                             Jack W. Crenshaw, Ph.D.
  33.  
  34.                                  31 August 1988
  35.  
  36.  
  37.                           Part VI: BOOLEAN EXPRESSIONS
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67. PA A
  68.  
  69.  
  70.  
  71.  
  72.  
  73.        *****************************************************************
  74.        *                                                               *
  75.        *                        COPYRIGHT NOTICE                       *
  76.        *                                                               *
  77.        *   Copyright (C) 1988 Jack W. Crenshaw. All rights reserved.   *
  78.        *                                                               *
  79.        *****************************************************************
  80.  
  81.  
  82.        INTRODUCTION
  83.  
  84.        In Part V of this series,  we  took a look at control constructs,
  85.        and developed parsing  routines  to  translate  them  into object
  86.        code.    We  ended  up  with  a  nice,  relatively  rich  set  of
  87.        constructs.
  88.  
  89.        As we left  the  parser,  though,  there  was one big hole in our
  90.        capabilities:  we  did  not  address  the  issue  of  the  branch
  91.        condition.  To fill the void,  I  introduced to you a dummy parse
  92.        routine called Condition, which only served as a place-keeper for
  93.        the real thing.
  94.  
  95.        One of the things we'll do in this session is  to  plug that hole
  96.        by expanding Condition into a true parser/translator.
  97.  
  98.  
  99.        THE PLAN
  100.  
  101.        We're going to  approach  this installment a bit differently than
  102.        any of the others.    In those other installments, we started out
  103.        immediately with experiments  using the Pascal compiler, building
  104.        up the parsers from  very  rudimentary  beginnings to their final
  105.        forms, without spending much time in planning  beforehand. That's
  106.        called coding without specs, and it's usually frowned  upon.   We
  107.        could get away with it before because the rules of arithmetic are
  108.        pretty well established ...  we  know what a '+' sign is supposed
  109.        to mean without having to discuss it at length.  The same is true
  110.        for branches and  loops.    But  the  ways  in  which programming
  111.        languages  implement  logic  vary quite a bit  from  language  to
  112.        language.  So before we begin serious coding,  we'd  better first
  113.        make up our minds what it is we want.  And the way to do  that is
  114.        at the level of the BNF syntax rules (the GRAMMAR).
  115.  
  116.  
  117.        THE GRAMMAR
  118.  
  119.        For some time  now,  we've been implementing BNF syntax equations
  120.        for arithmetic expressions, without  ever  actually  writing them
  121.        down all in one place.  It's time that we did so.  They are:
  122.  
  123.  
  124.             <expression> ::= <unary op> <term> [<addop> <term>]*
  125.             <term>       ::= <factor> [<mulop> factor]*
  126.             <factor>     ::= <integer> | <variable> | ( <expression> )A*A*
  127.                                      - 2 -
  128. PA A
  129.  
  130.  
  131.  
  132.  
  133.  
  134.        (Remember, the nice thing about  this grammar is that it enforces
  135.        the operator precedence hierarchy  that  we  normally  expect for
  136.        algebra.)
  137.  
  138.        Actually,  while we're on the subject, I'd  like  to  amend  this
  139.        grammar a bit right now.   The  way we've handled the unary minus
  140.        is  a  bit  awkward.  I've found that it's better  to  write  the
  141.        grammar this way:
  142.  
  143.  
  144.          <expression>    ::= <term> [<addop> <term>]*
  145.          <term>          ::= <signed factor> [<mulop> factor]*
  146.          <signed factor> ::= [<addop>] <factor>
  147.          <factor>        ::= <integer> | <variable> | (<expression>)
  148.  
  149.  
  150.        This puts the job of handling the unary minus onto  Factor, which
  151.        is where it really belongs.
  152.  
  153.        This  doesn't  mean  that  you  have  to  go  back and recode the
  154.        programs you've already written, although you're free to do so if
  155.        you like.  But I will be using the new syntax from now on.
  156.  
  157.        Now, it probably won't come as  a  shock  to you to learn that we
  158.        can define an analogous grammar for Boolean algebra.    A typical
  159.        set or rules is:
  160.  
  161.  
  162.         <b-expression>::= <b-term> [<orop> <b-term>]*
  163.         <b-term>      ::= <not-factor> [AND <not-factor>]*
  164.         <not-factor>  ::= [NOT] <b-factor>
  165.         <b-factor>    ::= <b-literal> | <b-variable> | (<b-expression>)
  166.  
  167.  
  168.        Notice that in this  grammar,  the  operator  AND is analogous to
  169.        '*',  and  OR  (and exclusive OR) to '+'.  The  NOT  operator  is
  170.        analogous to a unary  minus.    This  hierarchy is not absolutely
  171.        standard ...  some  languages,  notably  Ada,  treat  all logical
  172.        operators  as  having  the same precedence level ... but it seems
  173.        natural.
  174.  
  175.        Notice also the slight difference between the way the NOT and the
  176.        unary  minus  are  handled.    In  algebra,  the unary  minus  is
  177.        considered to go with the whole term, and so  never  appears  but
  178.        once in a given term. So an expression like
  179.  
  180.                            a * -b
  181.  
  182.        or worse yet,
  183.                            a - -b
  184.  
  185.        is not allowed.  In Boolean algebra, though, the expression
  186.  
  187.                            a AND NOT bA*A*
  188.                                      - 3 -
  189. PA A
  190.  
  191.  
  192.  
  193.  
  194.  
  195.        makes perfect sense, and the syntax shown allows for that.
  196.  
  197.  
  198.        RELOPS
  199.  
  200.        OK, assuming that you're willing to accept the grammar I've shown
  201.        here,  we  now  have syntax rules for both arithmetic and Boolean
  202.        algebra.    The  sticky part comes in when we have to combine the
  203.        two.  Why do we have to do that?  Well, the whole subject came up
  204.        because of the  need  to  process  the  "predicates" (conditions)
  205.        associated with control statements such as the IF.  The predicate
  206.        is required to have a Boolean value; that is, it must evaluate to
  207.        either TRUE or FALSE.  The branch is  then  taken  or  not taken,
  208.        depending  on  that  value.  What we expect to see  going  on  in
  209.        procedure  Condition,  then,  is  the  evaluation  of  a  Boolean
  210.        expression.
  211.  
  212.        But there's more to it than that.  A pure Boolean  expression can
  213.        indeed be the predicate of a control statement ... things like
  214.  
  215.  
  216.                  IF a AND NOT b THEN ....
  217.  
  218.  
  219.        But more often, we see Boolean algebra show up in such things as
  220.  
  221.  
  222.             IF (x >= 0) and (x <= 100) THEN ...
  223.  
  224.  
  225.        Here,  the  two  terms in parens are Boolean expressions, but the
  226.        individual terms being compared:  x,  0, and 100,  are NUMERIC in
  227.        nature.  The RELATIONAL OPERATORS >= and <= are the  catalysts by
  228.        which the  Boolean  and  the  arithmetic  ingredients  get merged
  229.        together.
  230.  
  231.        Now,  in the example above, the terms  being  compared  are  just
  232.        that:  terms.    However,  in  general  each  side  can be a math
  233.        expression.  So we can define a RELATION to be:
  234.  
  235.  
  236.             <relation> ::= <expression> <relop> <expression>  ,
  237.  
  238.  
  239.        where  the  expressions  we're  talking  about here are  the  old
  240.        numeric type, and the relops are any of the usual symbols
  241.  
  242.  
  243.                       =, <> (or !=), <, >, <=, and >=
  244.  
  245.  
  246.        If you think about it a  bit,  you'll agree that, since this kind
  247.        of predicate has a single Boolean value, TRUE or  FALSE,  as  itsA6A6
  248.                                      - 4 -A*A*
  249. PA A
  250.  
  251.  
  252.  
  253.  
  254.  
  255.        result, it is  really  just  another  kind  of factor.  So we can
  256.        expand the definition of a Boolean factor above to read:
  257.  
  258.  
  259.            <b-factor> ::=    <b-literal>
  260.                            | <b-variable>
  261.                            | (<b-expression>)
  262.                            | <relation>
  263.  
  264.  
  265.        THAT's the connection!  The relops and the  relation  they define
  266.        serve to wed the two kinds of algebra.  It  is  worth noting that
  267.        this implies a hierarchy  where  the  arithmetic expression has a
  268.        HIGHER precedence that  a  Boolean factor, and therefore than all
  269.        the  Boolean operators.    If you write out the precedence levels
  270.        for all the operators, you arrive at the following list:
  271.  
  272.  
  273.                  Level   Syntax Element     Operator
  274.  
  275.                  0       factor             literal, variable
  276.                  1       signed factor      unary minus
  277.                  2       term               *, /
  278.                  3       expression         +, -
  279.                  4       b-factor           literal, variable, relop
  280.                  5       not-factor         NOT
  281.                  6       b-term             AND
  282.                  7       b-expression       OR, XOR
  283.  
  284.  
  285.        If  we're willing to accept that  many  precedence  levels,  this
  286.        grammar seems reasonable.  Unfortunately,  it  won't  work!   The
  287.        grammar may be great in theory,  but  it's  no good at all in the
  288.        practice of a top-down parser.  To see the problem,  consider the
  289.        code fragment:
  290.  
  291.  
  292.             IF ((((((A + B + C) < 0 ) AND ....
  293.  
  294.  
  295.        When the parser is parsing this code, it knows after it  sees the
  296.        IF token that a Boolean expression is supposed to be next.  So it
  297.        can set up to begin evaluating such an expression.  But the first
  298.        expression in the example is an ARITHMETIC expression, A + B + C.
  299.        What's worse, at the point that the parser has read this  much of
  300.        the input line:
  301.  
  302.  
  303.             IF ((((((A   ,
  304.  
  305.  
  306.        it  still has no way of knowing which  kind  of  expression  it's
  307.        dealing  with.  That won't do, because  we  must  have  different
  308.        recognizers  for the two cases.  The  situation  can  be  handledA*A*
  309.                                      - 5 -
  310. PA A
  311.  
  312.  
  313.  
  314.  
  315.  
  316.        without  changing  any  of  our  definitions, but only  if  we're
  317.        willing to accept an arbitrary amount of backtracking to work our
  318.        way out of bad guesses.  No compiler  writer  in  his  right mind
  319.        would agree to that.
  320.  
  321.        What's going  on  here  is  that  the  beauty and elegance of BNF
  322.        grammar  has  met  face  to  face with the realities of  compiler
  323.        technology.
  324.  
  325.        To  deal  with  this situation, compiler writers have had to make
  326.        compromises  so  that  a  single  parser can handle  the  grammar
  327.        without backtracking.
  328.  
  329.  
  330.        FIXING THE GRAMMAR
  331.  
  332.        The  problem  that  we've  encountered  comes   up   because  our
  333.        definitions of both arithmetic and Boolean factors permit the use
  334.        of   parenthesized  expressions.    Since  the  definitions   are
  335.        recursive,  we  can  end  up  with  any  number   of   levels  of
  336.        parentheses, and the  parser  can't know which kind of expression
  337.        it's dealing with.
  338.  
  339.        The  solution is simple, although it  ends  up  causing  profound
  340.        changes to our  grammar.    We  can only allow parentheses in one
  341.        kind  of factor.  The way to do  that  varies  considerably  from
  342.        language  to  language.  This is one  place  where  there  is  NO
  343.        agreement or convention to help us.
  344.  
  345.        When Niklaus Wirth designed Pascal, the desire was  to  limit the
  346.        number of levels of precedence (fewer parse routines, after all).
  347.        So the OR  and  exclusive  OR  operators are treated just like an
  348.        Addop  and  processed   at   the  level  of  a  math  expression.
  349.        Similarly, the AND is  treated  like  a  Mulop and processed with
  350.        Term.  The precedence levels are
  351.  
  352.  
  353.                  Level   Syntax Element     Operator
  354.  
  355.                  0       factor             literal, variable
  356.                  1       signed factor      unary minus, NOT
  357.                  2       term               *, /, AND
  358.                  3       expression         +, -, OR
  359.  
  360.  
  361.        Notice that there is only ONE set of syntax  rules,  applying  to
  362.        both  kinds  of  operators.    According to this  grammar,  then,
  363.        expressions like
  364.  
  365.             x + (y AND NOT z) DIV 3
  366.  
  367.        are perfectly legal.  And, in  fact,  they  ARE ... as far as the
  368.        parser  is  concerned.    Pascal  doesn't  allow  the  mixing  of
  369.        arithmetic and Boolean variables, and things like this are caughtA*A*
  370.                                      - 6 -
  371. PA A
  372.  
  373.  
  374.  
  375.  
  376.  
  377.        at the SEMANTIC level, when it comes time to  generate  code  for
  378.        them, rather than at the syntax level.
  379.  
  380.        The authors of C took  a  diametrically  opposite  approach: they
  381.        treat the operators as  different,  and  have something much more
  382.        akin  to our seven levels of precedence.  In fact, in C there are
  383.        no fewer than 17 levels!  That's because C also has the operators
  384.        '=', '+=' and its kin, '<<', '>>', '++', '--', etc.   Ironically,
  385.        although in C the  arithmetic  and  Boolean operators are treated
  386.        separately, the variables are  NOT  ...  there  are no Boolean or
  387.        logical variables in  C,  so  a  Boolean  test can be made on any
  388.        integer value.
  389.  
  390.        We'll do something that's  sort  of  in-between.   I'm tempted to
  391.        stick  mostly  with  the Pascal approach, since  that  seems  the
  392.        simplest from an implementation point  of view, but it results in
  393.        some funnies that I never liked very much, such as the fact that,
  394.        in the expression
  395.  
  396.             IF (c >= 'A') and (c <= 'Z') then ...
  397.  
  398.        the  parens  above  are REQUIRED.  I never understood why before,
  399.        and  neither my compiler nor any human  ever  explained  it  very
  400.        well, either.  But now, we  can  all see that the 'and' operator,
  401.        having the precedence of a multiply, has a higher  one  than  the
  402.        relational operators, so without  the  parens  the  expression is
  403.        equivalent to
  404.  
  405.             IF c >= ('A' and c) <= 'Z' then
  406.  
  407.        which doesn't make sense.
  408.  
  409.        In  any  case,  I've  elected  to  separate  the  operators  into
  410.        different levels, although not as many as in C.
  411.  
  412.  
  413.         <b-expression> ::= <b-term> [<orop> <b-term>]*
  414.         <b-term>       ::= <not-factor> [AND <not-factor>]*
  415.         <not-factor>   ::= [NOT] <b-factor>
  416.         <b-factor>     ::= <b-literal> | <b-variable> | <relation>
  417.         <relation>     ::= | <expression> [<relop> <expression]
  418.         <expression>   ::= <term> [<addop> <term>]*
  419.         <term>         ::= <signed factor> [<mulop> factor]*
  420.         <signed factor>::= [<addop>] <factor>
  421.         <factor>       ::= <integer> | <variable> | (<b-expression>)
  422.  
  423.  
  424.        This grammar  results  in  the  same  set  of seven levels that I
  425.        showed earlier.  Really, it's almost the same grammar ...  I just
  426.        removed the option of parenthesized b-expressions  as  a possible
  427.        b-factor, and added the relation as a legal form of b-factor.
  428.  
  429.        There is one subtle but crucial difference, which  is  what makes
  430.        the  whole  thing  work.    Notice  the  square brackets  in  theA*A*
  431.                                      - 7 -
  432. PA A
  433.  
  434.  
  435.  
  436.  
  437.  
  438.        definition  of a relation.  This means that  the  relop  and  the
  439.        second expression are OPTIONAL.
  440.  
  441.        A strange consequence of this grammar (and one shared  by  C)  is
  442.        that EVERY expression  is  potentially a Boolean expression.  The
  443.        parser will always be looking  for a Boolean expression, but will
  444.        "settle" for an arithmetic one.  To be honest,  that's  going  to
  445.        slow down the parser, because it has to wade through  more layers
  446.        of procedure calls.  That's  one reason why Pascal compilers tend
  447.        to compile faster than C compilers.  If it's raw speed  you want,
  448.        stick with the Pascal syntax.
  449.  
  450.  
  451.        THE PARSER
  452.  
  453.        Now that we've gotten through the decision-making process, we can
  454.        press on with development of a parser.  You've done this  with me
  455.        several times now, so you know  the  drill: we begin with a fresh
  456.        copy of the cradle, and begin  adding  procedures one by one.  So
  457.        let's do it.
  458.  
  459.        We begin, as we did in the arithmetic case, by dealing  only with
  460.        Boolean literals rather than variables.  This gives us a new kind
  461.        of input token, so we're also going to need a new recognizer, and
  462.        a  new procedure to read instances of that  token  type.    Let's
  463.        start by defining the two new procedures:
  464.  
  465.  
  466.        {--------------------------------------------------------------}
  467.        { Recognize a Boolean Literal }
  468.  
  469.        function IsBoolean(c: char): Boolean;
  470.        begin
  471.           IsBoolean := UpCase(c) in ['T', 'F'];
  472.        end;
  473.  
  474.  
  475.        {--------------------------------------------------------------}
  476.        { Get a Boolean Literal }
  477.  
  478.        function GetBoolean: Boolean;
  479.        var c: char;
  480.        begin
  481.           if not IsBoolean(Look) then Expected('Boolean Literal');
  482.           GetBoolean := UpCase(Look) = 'T';
  483.           GetChar;
  484.        end;
  485.        {--------------------------------------------------------------}
  486.  
  487.  
  488.        Type  these routines into your program.  You  can  test  them  by
  489.        adding into the main program the print statementABAB
  490.                                      - 8 -A*A*
  491. PA A
  492.  
  493.  
  494.  
  495.  
  496.  
  497.           WriteLn(GetBoolean);
  498.  
  499.  
  500.        OK, compile the program and test it.   As  usual,  it's  not very
  501.        impressive so far, but it soon will be.
  502.  
  503.        Now, when we were dealing with numeric data we had to  arrange to
  504.        generate code to load the values into D0.  We need to do the same
  505.        for Boolean data.   The  usual way to encode Boolean variables is
  506.        to let 0 stand for FALSE,  and  some  other value for TRUE.  Many
  507.        languages, such as C, use an  integer  1  to represent it.  But I
  508.        prefer FFFF hex  (or  -1),  because  a bitwise NOT also becomes a
  509.        Boolean  NOT.  So now we need to emit the right assembler code to
  510.        load  those  values.    The  first cut at the Boolean  expression
  511.        parser (BoolExpression, of course) is:
  512.  
  513.  
  514.        {---------------------------------------------------------------}
  515.        { Parse and Translate a Boolean Expression }
  516.  
  517.        procedure BoolExpression;
  518.        begin
  519.           if not IsBoolean(Look) then Expected('Boolean Literal');
  520.           if GetBoolean then
  521.              EmitLn('MOVE #-1,D0')
  522.           else
  523.              EmitLn('CLR D0');
  524.        end;
  525.        {---------------------------------------------------------------}
  526.  
  527.  
  528.        Add  this procedure to your parser, and call  it  from  the  main
  529.        program (replacing the  print  statement you had just put there).
  530.        As you  can  see,  we  still don't have much of a parser, but the
  531.        output code is starting to look more realistic.
  532.  
  533.        Next, of course, we have to expand the definition  of  a  Boolean
  534.        expression.  We already have the BNF rule:
  535.  
  536.  
  537.         <b-expression> ::= <b-term> [<orop> <b-term>]*
  538.  
  539.  
  540.        I prefer the Pascal versions of the "orops",  OR  and  XOR.   But
  541.        since we are keeping to single-character tokens here, I'll encode
  542.        those with '|' and  '~'.  The  next  version of BoolExpression is
  543.        almost a direct copy of the arithmetic procedure Expression:A?A?
  544.  
  545.                                      - 9 -A*A*
  546. PA A
  547.  
  548.  
  549.  
  550.  
  551.  
  552.        {--------------------------------------------------------------}
  553.        { Recognize and Translate a Boolean OR }
  554.  
  555.        procedure BoolOr;
  556.        begin
  557.           Match('|');
  558.           BoolTerm;
  559.           EmitLn('OR (SP)+,D0');
  560.        end;
  561.  
  562.  
  563.        {--------------------------------------------------------------}
  564.        { Recognize and Translate an Exclusive Or }
  565.  
  566.        procedure BoolXor;
  567.        begin
  568.           Match('~');
  569.           BoolTerm;
  570.           EmitLn('EOR (SP)+,D0');
  571.        end;
  572.  
  573.  
  574.        {---------------------------------------------------------------}
  575.        { Parse and Translate a Boolean Expression }
  576.  
  577.        procedure BoolExpression;
  578.        begin
  579.           BoolTerm;
  580.           while IsOrOp(Look) do begin
  581.              EmitLn('MOVE D0,-(SP)');
  582.              case Look of
  583.               '|': BoolOr;
  584.               '~': BoolXor;
  585.              end;
  586.           end;
  587.        end;
  588.        {---------------------------------------------------------------}
  589.  
  590.  
  591.        Note the new recognizer  IsOrOp,  which is also a copy, this time
  592.        of IsAddOp:
  593.  
  594.  
  595.        {--------------------------------------------------------------}
  596.        { Recognize a Boolean Orop }
  597.  
  598.        function IsOrop(c: char): Boolean;
  599.        begin
  600.           IsOrop := c in ['|', '~'];
  601.        end;
  602.        {--------------------------------------------------------------}ANAN
  603.                                     - 10 -A*A*
  604. PA A
  605.  
  606.  
  607.  
  608.  
  609.  
  610.        OK, rename the old  version  of  BoolExpression to BoolTerm, then
  611.        enter  the  code  above.  Compile and test this version.  At this
  612.        point, the  output  code  is  starting  to  look pretty good.  Of
  613.        course, it doesn't make much sense to do a lot of Boolean algebra
  614.        on  constant values, but we'll soon be  expanding  the  types  of
  615.        Booleans we deal with.
  616.  
  617.        You've  probably  already  guessed  what  the next step  is:  The
  618.        Boolean version of Term.
  619.  
  620.        Rename the current procedure BoolTerm to NotFactor, and enter the
  621.        following new version of BoolTerm.  Note that is is  much simpler
  622.        than  the  numeric  version,  since  there  is  no equivalent  of
  623.        division.
  624.  
  625.  
  626.        {---------------------------------------------------------------}
  627.        { Parse and Translate a Boolean Term }
  628.  
  629.        procedure BoolTerm;
  630.        begin
  631.           NotFactor;
  632.           while Look = '&' do begin
  633.              EmitLn('MOVE D0,-(SP)');
  634.              Match('&');
  635.              NotFactor;
  636.              EmitLn('AND (SP)+,D0');
  637.           end;
  638.        end;
  639.        {--------------------------------------------------------------}
  640.  
  641.  
  642.        Now,  we're  almost  home.  We are  translating  complex  Boolean
  643.        expressions, although only for constant values.  The next step is
  644.        to allow for the NOT.  Write the following procedure:
  645.  
  646.  
  647.        {--------------------------------------------------------------}
  648.        { Parse and Translate a Boolean Factor with NOT }
  649.  
  650.        procedure NotFactor;
  651.        begin
  652.           if Look = '!' then begin
  653.              Match('!');
  654.              BoolFactor;
  655.              EmitLn('EOR #-1,D0');
  656.              end
  657.           else
  658.              BoolFactor;
  659.        end;
  660.        {--------------------------------------------------------------}ANAN
  661.                                     - 11 -A*A*
  662. PA A
  663.  
  664.  
  665.  
  666.  
  667.  
  668.        And  rename  the  earlier procedure to BoolFactor.  Now try that.
  669.        At this point  the  parser  should  be able to handle any Boolean
  670.        expression you care to throw at it.  Does it?  Does it trap badly
  671.        formed expressions?
  672.  
  673.        If you've  been  following  what  we  did  in the parser for math
  674.        expressions, you know  that  what  we  did next was to expand the
  675.        definition of a factor to include variables and parens.  We don't
  676.        have  to do that for the Boolean  factor,  because  those  little
  677.        items get taken care of by the next step.  It  takes  just  a one
  678.        line addition to BoolFactor to take care of relations:
  679.  
  680.  
  681.        {--------------------------------------------------------------}
  682.        { Parse and Translate a Boolean Factor }
  683.  
  684.        procedure BoolFactor;
  685.        begin
  686.           if IsBoolean(Look) then
  687.              if GetBoolean then
  688.                 EmitLn('MOVE #-1,D0')
  689.              else
  690.                 EmitLn('CLR D0')
  691.              else Relation;
  692.        end;
  693.        {--------------------------------------------------------------}
  694.  
  695.  
  696.        You  might be wondering when I'm going  to  provide  for  Boolean
  697.        variables and parenthesized Boolean expressions.  The  answer is,
  698.        I'm NOT!   Remember,  we  took  those out of the grammar earlier.
  699.        Right now all I'm  doing  is  encoding  the grammar we've already
  700.        agreed  upon.    The compiler itself can't  tell  the  difference
  701.        between a Boolean variable  or  expression  and an arithmetic one
  702.        ... all of those will be handled by Relation, either way.
  703.  
  704.  
  705.        Of course, it would help to have some code for Relation.  I don't
  706.        feel comfortable, though,  adding  any  more  code  without first
  707.        checking out what we already have.  So for now let's just write a
  708.        dummy  version  of  Relation  that  does nothing except  eat  the
  709.        current character, and write a little message:
  710.  
  711.  
  712.        {---------------------------------------------------------------}
  713.        { Parse and Translate a Relation }
  714.  
  715.        procedure Relation;
  716.        begin
  717.           WriteLn('<Relation>');
  718.           GetChar;
  719.        end;
  720.        {--------------------------------------------------------------}A6A6
  721.                                     - 12 -A*A*
  722. PA A
  723.  
  724.  
  725.  
  726.  
  727.  
  728.        OK, key  in  this  code  and  give  it a try.  All the old things
  729.        should still work ... you should be able to generate the code for
  730.        ANDs, ORs, and  NOTs.    In  addition, if you type any alphabetic
  731.        character you should get a little <Relation>  place-holder, where
  732.        a  Boolean factor should be.  Did you get that?  Fine, then let's
  733.        move on to the full-blown version of Relation.
  734.  
  735.        To  get  that,  though, there is a bit of groundwork that we must
  736.        lay first.  Recall that a relation has the form
  737.  
  738.  
  739.         <relation>     ::= | <expression> [<relop> <expression]
  740.  
  741.  
  742.        Since  we have a new kind of operator, we're also going to need a
  743.        new Boolean function to  recognize  it.    That function is shown
  744.        below.  Because of the single-character limitation,  I'm sticking
  745.        to the four operators  that  can be encoded with such a character
  746.        (the "not equals" is encoded by '#').
  747.  
  748.  
  749.        {--------------------------------------------------------------}
  750.        { Recognize a Relop }
  751.  
  752.        function IsRelop(c: char): Boolean;
  753.        begin
  754.           IsRelop := c in ['=', '#', '<', '>'];
  755.        end;
  756.        {--------------------------------------------------------------}
  757.  
  758.  
  759.        Now, recall  that  we're  using  a zero or a -1 in register D0 to
  760.        represent  a Boolean value, and also  that  the  loop  constructs
  761.        expect the flags to be set to correspond.   In  implementing  all
  762.        this on the 68000, things get a a little bit tricky.
  763.  
  764.        Since the loop constructs operate only on the flags, it  would be
  765.        nice (and also quite  efficient)  just to set up those flags, and
  766.        not load  anything  into  D0  at all.  This would be fine for the
  767.        loops  and  branches,  but remember that the relation can be used
  768.        ANYWHERE a Boolean factor could be  used.   We may be storing its
  769.        result to a Boolean variable.  Since we can't know at  this point
  770.        how the result is going to be used, we must allow for BOTH cases.
  771.  
  772.        Comparing numeric data  is  easy  enough  ...  the  68000  has an
  773.        operation  for  that ... but it sets  the  flags,  not  a  value.
  774.        What's more,  the  flags  will  always  be  set the same (zero if
  775.        equal, etc.), while we need the zero flag set differently for the
  776.        each of the different relops.
  777.  
  778.        The solution is found in the 68000 instruction Scc, which  sets a
  779.        byte value to 0000 or FFFF (funny how that works!) depending upon
  780.        the  result  of  the  specified   condition.    If  we  make  the
  781.        destination byte to be D0, we get the Boolean value needed.A*A*
  782.                                     - 13 -
  783. PA A
  784.  
  785.  
  786.  
  787.  
  788.  
  789.        Unfortunately,  there's one  final  complication:  unlike  almost
  790.        every other instruction in the 68000 set, Scc does NOT  reset the
  791.        condition flags to match the data being stored.  So we have to do
  792.        one last step, which is to test D0 and set the flags to match it.
  793.        It must seem to be a trip around the moon to get what we want: we
  794.        first perform the test, then test the flags to set data  into D0,
  795.        then test D0 to set the flags again.  It  is  sort of roundabout,
  796.        but it's the most straightforward way to get the flags right, and
  797.        after all it's only a couple of instructions.
  798.  
  799.        I  might  mention  here that this area is, in my opinion, the one
  800.        that represents the biggest difference between the  efficiency of
  801.        hand-coded assembler language and  compiler-generated  code.   We
  802.        have  seen  already  that  we  lose   efficiency   in  arithmetic
  803.        operations, although later I plan to show you how to improve that
  804.        a  bit.    We've also seen that the control constructs themselves
  805.        can be done quite efficiently  ... it's usually very difficult to
  806.        improve  on  the  code generated for an  IF  or  a  WHILE.    But
  807.        virtually every compiler I've ever seen generates  terrible code,
  808.        compared to assembler, for the computation of a Boolean function,
  809.        and particularly for relations.    The  reason  is just what I've
  810.        hinted at above.  When I'm writing code in assembler, I  go ahead
  811.        and perform the test the most convenient way I can, and  then set
  812.        up the branch so that it goes the way it should.    In  effect, I
  813.        "tailor"  every  branch  to the situation.  The compiler can't do
  814.        that (practically), and it also can't know that we don't  want to
  815.        store the result of the test as a Boolean variable.    So it must
  816.        generate  the  code  in a very strict order, and it often ends up
  817.        loading  the  result  as  a  Boolean  that  never gets  used  for
  818.        anything.
  819.  
  820.        In  any  case,  we're now ready to look at the code for Relation.
  821.        It's shown below with its companion procedures:
  822.  
  823.  
  824.        {---------------------------------------------------------------}
  825.        { Recognize and Translate a Relational "Equals" }
  826.  
  827.        procedure Equals;
  828.        begin
  829.           Match('=');
  830.           Expression;
  831.           EmitLn('CMP (SP)+,D0');
  832.           EmitLn('SEQ D0');
  833.        end;AKAK
  834.  
  835.                                     - 14 -A*A*
  836. PA A
  837.  
  838.  
  839.  
  840.  
  841.  
  842.        {---------------------------------------------------------------}
  843.        { Recognize and Translate a Relational "Not Equals" }
  844.  
  845.        procedure NotEquals;
  846.        begin
  847.           Match('#');
  848.           Expression;
  849.           EmitLn('CMP (SP)+,D0');
  850.           EmitLn('SNE D0');
  851.        end;
  852.  
  853.  
  854.        {---------------------------------------------------------------}
  855.        { Recognize and Translate a Relational "Less Than" }
  856.  
  857.        procedure Less;
  858.        begin
  859.           Match('<');
  860.           Expression;
  861.           EmitLn('CMP (SP)+,D0');
  862.           EmitLn('SGE D0');
  863.        end;
  864.  
  865.  
  866.        {---------------------------------------------------------------}
  867.        { Recognize and Translate a Relational "Greater Than" }
  868.  
  869.        procedure Greater;
  870.        begin
  871.           Match('>');
  872.           Expression;
  873.           EmitLn('CMP (SP)+,D0');
  874.           EmitLn('SLE D0');
  875.        end;
  876.  
  877.  
  878.        {---------------------------------------------------------------}
  879.        { Parse and Translate a Relation }
  880.  
  881.        procedure Relation;
  882.        begin
  883.           Expression;
  884.           if IsRelop(Look) then begin
  885.              EmitLn('MOVE D0,-(SP)');
  886.              case Look of
  887.               '=': Equals;
  888.               '#': NotEquals;
  889.               '<': Less;
  890.               '>': Greater;
  891.              end;
  892.           EmitLn('TST D0');
  893.           end;
  894.        end;
  895.        {---------------------------------------------------------------}A*A*
  896.                                     - 15 -
  897. PA A
  898.  
  899.  
  900.  
  901.  
  902.  
  903.        Now, that call to  Expression  looks familiar!  Here is where the
  904.        editor of your system comes in handy.  We have  already generated
  905.        code  for  Expression  and its buddies in previous sessions.  You
  906.        can  copy  them  into your file now.  Remember to use the single-
  907.        character  versions.  Just to be  certain,  I've  duplicated  the
  908.        arithmetic procedures below.  If  you're  observant,  you'll also
  909.        see that I've changed them a little to make  them  correspond  to
  910.        the latest version of the syntax.  This change is  NOT necessary,
  911.        so  you  may  prefer  to  hold  off  on  that  until you're  sure
  912.        everything is working.
  913.  
  914.  
  915.        {---------------------------------------------------------------}
  916.        { Parse and Translate an Identifier }
  917.  
  918.        procedure Ident;
  919.        var Name: char;
  920.        begin
  921.           Name:= GetName;
  922.           if Look = '(' then begin
  923.              Match('(');
  924.              Match(')');
  925.              EmitLn('BSR ' + Name);
  926.              end
  927.           else
  928.              EmitLn('MOVE ' + Name + '(PC),D0');
  929.        end;
  930.  
  931.  
  932.        {---------------------------------------------------------------}
  933.        { Parse and Translate a Math Factor }
  934.  
  935.        procedure Expression; Forward;
  936.  
  937.        procedure Factor;
  938.        begin
  939.           if Look = '(' then begin
  940.              Match('(');
  941.              Expression;
  942.              Match(')');
  943.              end
  944.           else if IsAlpha(Look) then
  945.              Ident
  946.           else
  947.              EmitLn('MOVE #' + GetNum + ',D0');
  948.        end;AEAE
  949.  
  950.                                     - 16 -A*A*
  951. PA A
  952.  
  953.  
  954.  
  955.  
  956.  
  957.        {---------------------------------------------------------------}
  958.        { Parse and Translate the First Math Factor }
  959.  
  960.  
  961.        procedure SignedFactor;
  962.        begin
  963.           if Look = '+' then
  964.              GetChar;
  965.           if Look = '-' then begin
  966.              GetChar;
  967.              if IsDigit(Look) then
  968.                 EmitLn('MOVE #-' + GetNum + ',D0')
  969.              else begin
  970.                 Factor;
  971.                 EmitLn('NEG D0');
  972.              end;
  973.           end
  974.           else Factor;
  975.        end;
  976.  
  977.  
  978.        {--------------------------------------------------------------}
  979.        { Recognize and Translate a Multiply }
  980.  
  981.        procedure Multiply;
  982.        begin
  983.           Match('*');
  984.           Factor;
  985.           EmitLn('MULS (SP)+,D0');
  986.        end;
  987.  
  988.  
  989.        {-------------------------------------------------------------}
  990.        { Recognize and Translate a Divide }
  991.  
  992.        procedure Divide;
  993.        begin
  994.           Match('/');
  995.           Factor;
  996.           EmitLn('MOVE (SP)+,D1');
  997.           EmitLn('EXS.L D0');
  998.           EmitLn('DIVS D1,D0');
  999.        end;A:A:
  1000.  
  1001.  
  1002.                                     - 17 -A*A*
  1003. PA A
  1004.  
  1005.  
  1006.  
  1007.  
  1008.  
  1009.        {---------------------------------------------------------------}
  1010.        { Parse and Translate a Math Term }
  1011.  
  1012.        procedure Term;
  1013.        begin
  1014.           SignedFactor;
  1015.           while Look in ['*', '/'] do begin
  1016.              EmitLn('MOVE D0,-(SP)');
  1017.              case Look of
  1018.               '*': Multiply;
  1019.               '/': Divide;
  1020.              end;
  1021.           end;
  1022.        end;
  1023.  
  1024.  
  1025.        {---------------------------------------------------------------}
  1026.        { Recognize and Translate an Add }
  1027.  
  1028.        procedure Add;
  1029.        begin
  1030.           Match('+');
  1031.           Term;
  1032.           EmitLn('ADD (SP)+,D0');
  1033.        end;
  1034.  
  1035.  
  1036.        {---------------------------------------------------------------}
  1037.        { Recognize and Translate a Subtract }
  1038.  
  1039.        procedure Subtract;
  1040.        begin
  1041.           Match('-');
  1042.           Term;
  1043.           EmitLn('SUB (SP)+,D0');
  1044.           EmitLn('NEG D0');
  1045.        end;
  1046.  
  1047.  
  1048.        {---------------------------------------------------------------}
  1049.        { Parse and Translate an Expression }
  1050.  
  1051.        procedure Expression;
  1052.        begin
  1053.           Term;
  1054.           while IsAddop(Look) do begin
  1055.              EmitLn('MOVE D0,-(SP)');
  1056.              case Look of
  1057.               '+': Add;
  1058.               '-': Subtract;
  1059.              end;
  1060.           end;
  1061.        end;
  1062.        {---------------------------------------------------------------}A*A*
  1063.                                     - 18 -
  1064. PA A
  1065.  
  1066.  
  1067.  
  1068.  
  1069.  
  1070.        There you have it ... a parser that can  handle  both  arithmetic
  1071.        AND Boolean algebra, and things  that combine the two through the
  1072.        use of relops.   I suggest you file away a copy of this parser in
  1073.        a safe place for future reference, because in our next step we're
  1074.        going to be chopping it up.
  1075.  
  1076.  
  1077.        MERGING WITH CONTROL CONSTRUCTS
  1078.  
  1079.        At this point, let's go back to the file we had  previously built
  1080.        that parses control  constructs.    Remember  those  little dummy
  1081.        procedures called Condition and  Expression?    Now you know what
  1082.        goes in their places!
  1083.  
  1084.        I  warn you, you're going to have to  do  some  creative  editing
  1085.        here, so take your time and get it right.  What you need to do is
  1086.        to copy all of  the  procedures from the logic parser, from Ident
  1087.        through  BoolExpression, into the parser for control  constructs.
  1088.        Insert  them  at  the current location of Condition.  Then delete
  1089.        that  procedure,  as  well as the dummy Expression.  Next, change
  1090.        every call  to  Condition  to  refer  to  BoolExpression instead.
  1091.        Finally, copy the procedures IsMulop, IsOrOp, IsRelop, IsBoolean,
  1092.        and GetBoolean into place.  That should do it.
  1093.  
  1094.        Compile  the  resulting program and give it  a  try.    Since  we
  1095.        haven't  used  this  program in awhile, don't forget that we used
  1096.        single-character tokens for IF,  WHILE,  etc.   Also don't forget
  1097.        that any letter not a keyword just gets echoed as a block.
  1098.  
  1099.        Try
  1100.  
  1101.             ia=bxlye
  1102.  
  1103.        which stands for "IF a=b X ELSE Y ENDIF".
  1104.  
  1105.        What do you think?  Did it work?  Try some others.
  1106.  
  1107.  
  1108.        ADDING ASSIGNMENTS
  1109.  
  1110.        As long as we're this far,  and  we already have the routines for
  1111.        expressions in place, we might  as well replace the "blocks" with
  1112.        real assignment statements.    We've already done that before, so
  1113.        it won't be too hard.   Before  taking that step, though, we need
  1114.        to fix something else.
  1115.  
  1116.        We're soon going to find  that the one-line "programs" that we're
  1117.        having to write here will really cramp our style.  At  the moment
  1118.        we  have  no  cure for that, because our parser doesn't recognize
  1119.        the end-of-line characters, the carriage return (CR) and the line
  1120.        feed (LF).  So before going any further let's plug that hole.
  1121.  
  1122.        There are  a  couple  of  ways to deal with the CR/LFs.  One (the
  1123.        C/Unix approach) is just to  treat them as additional white spaceA*A*
  1124.                                     - 19 -
  1125. PA A
  1126.  
  1127.  
  1128.  
  1129.  
  1130.  
  1131.        characters  and  ignore  them.    That's actually not such a  bad
  1132.        approach,  but  it  does  sort  of produce funny results for  our
  1133.        parser as  it  stands  now.   If it were reading its input from a
  1134.        source file as  any  self-respecting  REAL  compiler  does, there
  1135.        would be no problem.  But we're reading input from  the keyboard,
  1136.        and we're sort of conditioned  to expect something to happen when
  1137.        we hit the return key.  It won't, if we just skip over the CR and
  1138.        LF  (try it).  So I'm going to use a different method here, which
  1139.        is NOT necessarily the  best  approach in the long run.  Consider
  1140.        it a temporary kludge until we're further along.
  1141.  
  1142.        Instead of skipping the CR/LF,  We'll let the parser go ahead and
  1143.        catch them, then  introduce  a  special  procedure,  analogous to
  1144.        SkipWhite, that skips them only in specified "legal" spots.
  1145.  
  1146.        Here's the procedure:
  1147.  
  1148.  
  1149.        {--------------------------------------------------------------}
  1150.        { Skip a CRLF }
  1151.  
  1152.        procedure Fin;
  1153.        begin
  1154.           if Look = CR then GetChar;
  1155.           if Look = LF then GetChar;
  1156.        end;
  1157.  
  1158.        {--------------------------------------------------------------}
  1159.  
  1160.  
  1161.        Now, add two calls to Fin in procedure Block, like this:
  1162.  
  1163.  
  1164.        {--------------------------------------------------------------}
  1165.        { Recognize and Translate a Statement Block }
  1166.  
  1167.        procedure Block(L: string);
  1168.        begin
  1169.           while not(Look in ['e', 'l', 'u']) do begin
  1170.              Fin;
  1171.              case Look of
  1172.               'i': DoIf(L);
  1173.               'w': DoWhile;
  1174.               'p': DoLoop;
  1175.               'r': DoRepeat;
  1176.               'f': DoFor;
  1177.               'd': DoDo;
  1178.               'b': DoBreak(L);
  1179.               else Other;
  1180.              end;
  1181.              Fin;
  1182.         end;
  1183.        end;
  1184.        {--------------------------------------------------------------}A*A*
  1185.                                     - 20 -
  1186. PA A
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.        Now, you'll find that you  can use multiple-line "programs."  The
  1193.        only restriction is that you can't separate an IF or  WHILE token
  1194.        from its predicate.
  1195.  
  1196.        Now we're ready to include  the  assignment  statements.   Simply
  1197.        change  that  call  to  Other  in  procedure  Block  to a call to
  1198.        Assignment, and add  the  following procedure, copied from one of
  1199.        our  earlier  programs.     Note   that   Assignment   now  calls
  1200.        BoolExpression, so that we can assign Boolean variables.
  1201.  
  1202.  
  1203.        {--------------------------------------------------------------}
  1204.        { Parse and Translate an Assignment Statement }
  1205.  
  1206.        procedure Assignment;
  1207.        var Name: char;
  1208.        begin
  1209.           Name := GetName;
  1210.           Match('=');
  1211.           BoolExpression;
  1212.           EmitLn('LEA ' + Name + '(PC),A0');
  1213.           EmitLn('MOVE D0,(A0)');
  1214.        end;
  1215.        {--------------------------------------------------------------}
  1216.  
  1217.  
  1218.        With  that change, you should now be  able  to  write  reasonably
  1219.        realistic-looking  programs,  subject  only  to our limitation on
  1220.        single-character tokens.  My original intention was to get rid of
  1221.        that limitation for you, too.  However, that's going to require a
  1222.        fairly major change to what we've  done  so  far.  We need a true
  1223.        lexical scanner, and that requires some structural changes.  They
  1224.        are not BIG changes that require us to  throw  away  all  of what
  1225.        we've done so far ... with care, it can be done with very minimal
  1226.        changes, in fact.  But it does require that care.
  1227.  
  1228.        This installment  has already gotten pretty long, and it contains
  1229.        some pretty heavy stuff, so I've decided to leave that step until
  1230.        next  time, when you've had a little more  time  to  digest  what
  1231.        we've done and are ready to start fresh.
  1232.  
  1233.        In the next installment, then,  we'll build a lexical scanner and
  1234.        eliminate the single-character  barrier  once and for all.  We'll
  1235.        also write our first complete  compiler, based on what we've done
  1236.        in this session.  See you then.
  1237.  
  1238.  
  1239.        *****************************************************************
  1240.        *                                                               *
  1241.        *                        COPYRIGHT NOTICE                       *
  1242.        *                                                               *
  1243.        *   Copyright (C) 1988 Jack W. Crenshaw. All rights reserved.   *
  1244.        *                                                               *
  1245.        *****************************************************************A*A*
  1246.                                     - 21 -
  1247. @